import _extends from 'babel-runtime/helpers/extends';
import Loading from '../components/loading';
import api from '../libs/api';
import '../libs/promise.finally';

export default function loadingMiddleware(_ref) {
  var dispatch = _ref.dispatch,
      getState = _ref.getState;

  return function (next) {
    return function (action) {
      var promise = action.promise,
          _action$meta = action.meta,
          meta = _action$meta === undefined ? { suppressLoading: false } : _action$meta;


      if (!promise) {
        return next(action);
      }

      if (!meta.suppressLoading) {
        Loading.show();
      }

      var actionPromise = promise(dispatch, getState, api);

      function finallyHandler() {
        if (!meta.suppressLoading) {
          Loading.hide();
        }
      }

      actionPromise.finally(finallyHandler);

      return next(_extends({}, action, { promise: actionPromise }));
    };
  };
}